<!DOCTYPE html>
<html>

<head>
  <title>vue 登录验证</title>
  <script src="./static/js/vue.min.js"></script>
  <script src="./static/js/vue-router.js"></script>
</head>

<body>
  <div id="app">
    <h1>Router test</h1>
    <p>
      <router-link to='/list'>Go List</router-link>
      <router-link to='/add'>Go Add</router-link>
    </p>
    <router-view></router-view>
  </div>

  <script>
    var login = false
    const List = { template: '<div>list</div>' }
    const Add = {
      template: '<div>Add</div>',
      beforeRouteEnter: (to, from, next) => {
        if (!login) {
          next({ path: '/login' })
        }
      }
    }
    const Login = { template: '<div>Login</div>' }
    const router = new VueRouter({
      routes: [
        { path: '/list', component: List },
        { path: '/login', component: Login },
        { path: '/add', component: Add, meta: { needLogin: true } }
      ]
    })
    const router2 = new VueRouter({
      routes: [
        { path: '/list', component: List },
        { path: '/login', component: Login },
        {
          path: '/add', component: Add,
          beforeEnter: (to, from, next) => {
            if (!login) {
              next({ path: '/login' })
            }
          }
        }
      ]
    })
    router.beforeEach((to, from, next) => {
      if (to.meta.needLogin && !login) {
        next({ path: '/login' })
      } else {
        next()
      }
    })
    const app = new Vue({
      el: '#app',
      router
    })
  </script>

</body>


</html>
